<script setup>
import { ref, reactive, onMounted, onUnmounted, getCurrentInstance } from "vue";
import { addWMTSLayer, flyTo } from '@/components/leaflet/leafletMap'
import { getAxios, update } from '@/api/global'
import WKT from 'wkt'
import * as turf from '@turf/turf';
import { ElMessage } from "element-plus";




const { appContext } = getCurrentInstance();
let global = appContext.config.globalProperties;


let layerObj = ref('')
let layertype = ref('')

let serverLayer = null

const props = defineProps({
  serverData: {
    type: Object
  }
});


//是否编辑
let isEdit = ref(false)
//操作是否完成
let isFinish = ref(false)
//对象的fid
let fid = ref('')

//对象集合
let obj = reactive({
  showLayer: null,
  geojsonObj: {}
})

onMounted(() => {
  console.log(props.serverData, 123)
  const { extent, serviceName, styleId } = props.serverData
  addServer(serviceName, styleId)

  let bounds = L.latLngBounds([
    [extent[3], extent[1]],
    [extent[2], extent[0]]
  ])
  global.$map.fitBounds(bounds)
})

onUnmounted(() => {
  cancelLayer()
  global.$map.removeLayer(serverLayer)
})

const addServer = (serviceName, styleId) => {
  serverLayer = addWMTSLayer(global.$map, `${window.BaseUrl}mapserver/layer/${serviceName}/getMAP?l={z}&y={y}&x={x}&styleId=${styleId}`)
  addListen()
}

//添加监听
const addListen = () => {
  global.$map.on('click', (event) => {
    if (isEdit.value) {
      return
    }
    // 处理点击事件，event.latlng 提供点击位置的经纬度
    cancelLayer()
    getfeatureByServer(event.latlng)
  });

}

const getfeatureByServer = async (latlng) => {
  const bufferPoint = getBufferPosition('point', [latlng.lng, latlng.lat], 4);
  if (bufferPoint.length == 0) return;
  let bufferStr = '';
  bufferPoint.forEach((item, index) => {
    if (index !== 0 && index + 1 !== bufferPoint.length && index % 2 !== 0) {
      bufferStr += `${item}, `;
    } else {
      bufferStr += `${item} `;
    }
  });
  const urlParms = `POLYGON((${bufferStr}))`;

  const { serviceName } = props.serverData

  const url = `${window.BaseUrl}mapserver/${serviceName}/${serviceName}/query?spatialFilter=${urlParms}&withGeometry=true`
  const res = await getAxios(url)
  if (res && res.length > 0) {
    fid.value = res[0].fid
    isEdit.value = true
    obj.geojsonObj = WKT.parse(res[0].geom)
    console.log(obj.geojsonObj)
    switch (obj.geojsonObj.type) {
      case 'Point':
        handleArr(obj.geojsonObj.coordinates, 'marker')
        break
      case 'LineString':
        handleArr(obj.geojsonObj.coordinates, 'LineString')
        break
      case 'Polygon':
        handleArr(obj.geojsonObj.coordinates[0], 'polygon')
        break
      case 'MultiPoint':
        handleArr(obj.geojsonObj.coordinates, 'marker')
        break
      case 'MultiLineString':
        handleArr(obj.geojsonObj.coordinates[0], 'polyline')
        break
      case 'MultiPolygon':
        handleArr(obj.geojsonObj.coordinates[0][0], 'MultiPolygon')
        break
    }
  }
}
function handleArr (arr, type) {
  let latlngs = []
  arr.forEach(item => {
    latlngs.push([item[1], item[0]])
  })
  layertype.value = type
  switch (type) {
    case 'marker':
      layerObj.value = L.marker([arr[1], arr[0]]).addTo(global.$map)
      break;
    case 'LineString':
      layerObj.value = L.polyline(latlngs, { latlngs: '#6495ED' }).addTo(global.$map)
      break;
    case 'polyline':
      layerObj.value = L.polyline(latlngs, { latlngs: '#6495ED' }).addTo(global.$map)
      break;
    case 'polygon':
      layerObj.value = L.polygon(latlngs, { color: '#6495ED' }).addTo(global.$map)
  }
}

//编辑图层
const editLayer = () => {
  isFinish.value = true
  layerObj.value.pm.enable({
    allowSelfIntersection: false,
  })
  layerObj.value.on('pm:edit', (e) => {
    console.log(e);
  });

  layerObj.value.on('pm:disable', (e) => {
    let arr = []
    switch (layertype.value) {
      case 'marker':
        arr = [e.layer._latlng.lng, e.layer._latlng.lat]
        obj.geojsonObj.coordinates = arr
        break;
      case 'LineString':
        e.layer._latlngs.forEach(item => {
          arr.push([item.lng, item.lat])
        })
        obj.geojsonObj.coordinates = arr
        break;
      case 'polyline':
        e.layer._latlngs.forEach(item => {
          arr.push([item.lng, item.lat])
        })
        obj.geojsonObj.coordinates[0] = arr
        break;
      case 'polygon':
        e.layer._latlngs[0].forEach(item => {
          arr.push([item.lng, item.lat])
        })
        //补一个起点
        arr.push(arr[0])
        obj.geojsonObj.coordinates[0] = arr
        break;
      case 'MultiPolygon':
        e.layer._latlngs[0].forEach(item => {
          arr.push([item.lng, item.lat])
        })
        obj.geojsonObj.coordinates[0][0] = arr
        break;
    }
    let wkt = WKT.stringify(obj.geojsonObj)
    updateData(wkt)
  });
}

const updateData = async (wkt) => {
  const res = await update({
    tableName: props.serverData.serviceName,
    key: fid.value,
    wkt
  })

  if (res.status === 'OK') {
    ElMessage({
      type: "success",
      message: "更新成功",
    });
    global.$map.removeLayer(serverLayer)
    serverLayer = null

    let date = new Date();
    let timestamp = date.getTime();
    const { serviceName, styleId } = props.serverData
    serverLayer = addWMTSLayer(global.$map, `${window.BaseUrl}mapserver/layer/${serviceName}/getMAP?l={z}&y={y}&x={x}&styleId=${styleId}&${timestamp}`)
  } else {
    ElMessage({
      type: "warning",
      message: "更新失败",
    });
  }
}

// 缓冲
function getBufferPosition (type, oldPosition, radius = 4) {
  let polygonF = null;
  switch (type) {
    case 'point':
      polygonF = turf.point(oldPosition);
      break;
    case 'lineString':
      polygonF = turf.lineString(oldPosition);
      break;
    case 'polygon':
      var firstPoint = oldPosition[0];
      var lastPoint = oldPosition[oldPosition.length - 1];
      var status = firstPoint.length === lastPoint.length && firstPoint.sort().toString() === lastPoint.sort().toString();
      if (status == false) {
        oldPosition.push(firstPoint);
      }
      if (oldPosition[0]) polygonF = turf.polygon([oldPosition]);
      break;
    default:
      break;
  }

  if (polygonF) {
    const buffered = turf.buffer(polygonF, radius, { units: 'meters' });
    const coordinates = buffered.geometry.coordinates;
    const bufferPosition = coordinates[0];
    const newPositions = [].concat(...bufferPosition);
    return newPositions;
  }
}

//完成图层
const finishLayer = () => {
  isEdit.value = false
  isFinish.value = false
  layerObj.value.pm.disable()
  global.$map.removeLayer(layerObj.value)
}

//取消图层选择
const cancelLayer = () => {
  if (layerObj.value) {
    isEdit.value = false
    global.$map.removeLayer(layerObj.value)
  }
}


</script>

<template>
  <div>
    <el-button @click="editLayer" :disabled="!isEdit" type="primary">编辑</el-button>
    <el-button @click="finishLayer" :disabled="!isFinish" type="success">完成</el-button>
    <el-button @click="cancelLayer" type="warning">取消图层</el-button>
  </div>
</template>

